package com.movieknight;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.ListActivity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;

/**
 * Our main activity, show a list of Friends, Checks and allows to select some of them
 * 
 * @author marvinlabs
 */
public class FriendDeleteActivity extends ListActivity {
	private static final String LOG_TAG = TMDBMovieDownloader.class.getSimpleName();
	private SQLFriendsDataSource datasource;
	
	private List<Friend> data;
	private ListView listView;
	private FriendDeleteListAdapter adapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
        
		datasource = new SQLFriendsDataSource(this);
		datasource.open();
		data = datasource.getAllFriends();
		
		setContentView(R.layout.friend_delete);
		
        refreshFriends();
		

		/*// Create the adapter to render our data
		// --
		adapter = new FriendDeleteListAdapter(this, data);
		setListAdapter(adapter);

		// Get some views for later use
		// --
		listView = getListView();
		listView.setItemsCanFocus(false);
		
		listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);*/
	}

	/**
	 * Called when the user presses one of the buttons in the main view
	 */
	public void onButtonClick(View v) {
		switch (v.getId()) {
		case R.id.removeFriendsButton:
			returnSelectedFriendCheckIds();
			break;
		case R.id.cancelButton:
			setResult(RESULT_OK);
			finish();
			break;
		}
	}

	/**
	 * Show a message giving the selected MovieCheck IDs. There seems to be a bug with
	 * ListView#getCheckMovieCheckIds() on Android 1.6 at least @see
	 * http://code.google.com/p/android/issues/detail?id=6609
	 */
	private void returnSelectedFriendCheckIds() {
		// Get an array that contains the IDs of the list MovieChecks that are checked
		// --
		final long[] checkedFriendIds = listView.getCheckItemIds();
		if (checkedFriendIds == null) {
			Toast.makeText(this, "No selection", Toast.LENGTH_LONG).show();
			return;
		}

		// For each ID in the status array
		// --
		final int checkedFriendCount = checkedFriendIds.length;
		for (int i = 0; i < checkedFriendCount; ++i) {
			// SERVER: Delete friends with ID: adapter.getFriendId((int)checkedFriendIds[i])
			Socket server = ((MovieKnightApp) this.getApplication()).getServer();
			String sessionID = ((MovieKnightApp) this.getApplication()).getSessionID();
			int tempError = -1;
			
			PrintWriter out = null;
			try {
				out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(server.getOutputStream())), true);
			
			out.println("{\"module\": \"movies\", \"method\": \"del_friend\",\"session_id\": \"" + sessionID + "\", \"params\": {\"friend_username\": \"" + adapter.getFriendName((int)checkedFriendIds[i]) + "\"}}");
			
			BufferedReader input;
			String st = null;
	        input = new BufferedReader(new InputStreamReader(server.getInputStream()));    
			st = input.readLine();//Get Response from Server		
			JSONObject jsonObject = null;	
			
			//Parse response
			try {
				jsonObject = new JSONObject(st);
			
		
				//Error Code
				tempError = Integer.parseInt(jsonObject.getString("error_code"));
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//END SERVER ------------------------------------------------------
			
			if(tempError ==0)
			{
				datasource.deleteFriend(adapter.getFriendId((int)checkedFriendIds[i]));
				Log.w(LOG_TAG, "Removed friend " + checkedFriendIds[i]);
			}
		}

		setResult(RESULT_OK);
		finish();
	}
	
	public void refreshFriends(){
		// SERVER: Refresh Friends List
					if(data!=null)
						data.clear();
					Socket server = ((MovieKnightApp) this.getApplication()).getServer();
					String sessionID = ((MovieKnightApp) this.getApplication()).getSessionID();
					int tempError = -1;
							
					PrintWriter out = null;
					try {
						out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(server.getOutputStream())), true);	
						out.println("{\"module\": \"movies\", \"method\": \"get_friends\",\"session_id\": \"" + sessionID + "\"}");
								
						BufferedReader input = null;
						String st = null;
						input = new BufferedReader(new InputStreamReader(server.getInputStream()));    
						st = input.readLine();//Get Response from Server		
						JSONObject jsonObject = null;
						JSONArray jsonArray = null;
							
						//Parse response
						try {
							jsonObject = new JSONObject(st);
							jsonArray = jsonObject.getJSONArray("friends");
						
							//Error Code
							tempError = Integer.parseInt(jsonObject.getString("error_code"));
							
						//END SERVER ------------------------------------------------------
						
						if(tempError ==0)
						{
							for(int i = 0; i < jsonArray.length(); i++){
								Friend tempFriend = new Friend((long)i,jsonArray.getString(i));
								data.add(i,tempFriend);
								Log.v("friend", jsonArray.getString(i));
							}
							
			    			adapter = new FriendDeleteListAdapter(this, data);
			    			setListAdapter(adapter);

			    			listView = getListView();
			    			listView.setItemsCanFocus(false);
			    			listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
						}
						
						} catch (JSONException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
	}
	
}